package com.yueqian.system.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@Slf4j
public class MqController {

	private final RabbitTemplate rabbitTemplate;

	@GetMapping("/test/producerTest")
	public void producerTest() {
		//准备一个CorrelationData对象
		CorrelationData data = new CorrelationData();
		//设置消息的id。为了防止ACK结果混乱，我们给每条消息指定一个唯一标识
		data.setId(UUID.randomUUID().toString());
		Message message = MessageBuilder
								  .withBody("hello".getBytes())
								  //设置为持久化消息
								  .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
								  .build();
		rabbitTemplate.convertAndSend("topic_exchange", "topic", message, data);
	}

	@RabbitListener(queuesToDeclare = @Queue("topic_queue"))
	public void handleProduceQueueMsg(String msg) {
		log.info("从{}队列接收到消息：{}", "topic_queue", msg);
		//模拟：处理消息中出现了异常
		int i = 1 / 0;
		System.out.println("模拟：处理消息中……");
		log.info("消息处理完毕");
	}


	@RabbitListener(queuesToDeclare = @Queue("error_queue"))
	public void handleErrorMsg(String msg) {
		log.info("从{}接收到消息：{}", "error_queue", msg);
	}


	@GetMapping("/test/produceOrder")
	public void produceOrder(@RequestParam(value = "orderId") String orderId) {
		String msg = "这是一条延迟消息，发送时间是：" + DateUtil.now();
		Message message = MessageBuilder.withBody(msg.getBytes())
								  .setHeader("x-delay", 5000)
								  .build();
		rabbitTemplate.convertAndSend("delay.direct.exchange", "delay", message);
	}

	@RabbitListener(bindings = @QueueBinding(value = @Queue("delay.queue"), exchange = @Exchange(value = "delay.direct.exchange", type = ExchangeTypes.DIRECT, delayed = "true"), key = "delay"))
	public void handleOrderCancel(String msg) {
		// 取消订单逻辑
		log.info("现在时间是：{}，从{}队列接收到消息：{}", DateUtil.now(), "delay.queue", msg);
		// ...
	}
}
